package cn.golxen.rsms.commons.utils;

import cn.golxen.rsms.bean.entity.EmployeeMain;
import cn.golxen.rsms.bean.entity.UserMain;
import cn.golxen.rsms.exception.exceptionClass.AuthorityException;
import cn.golxen.rsms.exception.exceptionClass.GetTokenException;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JWTUtils {
    //服务器密钥
    static final String secret="Golxen666";
    public static String createJwtToken(String jsonStr){
        Date date = LocalDateTimeUtils.toDate();
        //token加密
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setIssuer("Golxen")
                .setSubject(jsonStr)
                .setIssuedAt(date)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }
    public static boolean isExpires(String token){
        Claims claims= Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return LocalDateTimeUtils.toDate().getTime()>claims.getExpiration().getTime();
    }
    public static void verifyJWT(String token,String url) throws RuntimeException{
        String module=url.split("/")[1];
        Claims claims;
        EmployeeMain employeeMain = new EmployeeMain();
        try {
            //token正确性验证
            claims= Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            e.printStackTrace();
            throw new GetTokenException();

        }
        try {
            //权限验证
            employeeMain=JSONObject.parseObject(claims.getSubject(), EmployeeMain.class);
            if (!url.equals("/store/loginEmployeeMain")){
                switch (employeeMain.getAuth()){
                    case 1:
                        if(!module.equals("pay")&&!module.equals("goods"))
                            throw new AuthorityException();
                        break;
                    case 2:
                        if(!module.equals("goods"))
                            throw new AuthorityException();
                        break;
                    case 3:
                        if(!module.equals("pay"))
                            throw new AuthorityException();
                        break;
                }
            }
        }catch (Exception e){
            if (e.getMessage()!=null){
                if (e.getMessage().equals("没有此权限"))
                    throw new AuthorityException();
            }
        }

    }
}
